﻿using UnityEngine;
using UnityEditor;
using System;
namespace SimpleNodeBasedEditor
{
    public class MainNodeEditorWindow : EditorWindow
    {
        private bool isLoad = false;
        private MainDataScriptableObject mainData;
        public Vector2 EditorWindowScrollPosition = Vector2.zero;
  

        void OnGUI()
        {
            minSize = new Vector2(400, 400);

            GUI.Label(new Rect((position.width - 200) / 2 - 15, 5, position.width - 200, 30), "编辑器主工作区域");
            DrawLeftWindow();

            EditorWindowScrollPosition = GUI.BeginScrollView(new Rect(0, 20, position.width - 200, position.height - 20), EditorWindowScrollPosition, new Rect(0, 0, 2560, 1440), true, true);
            if (mainData != null)
            {
                if (!isLoad)
                {
                    NodeWindowManager.Instance.FirstLoad(mainData);
                    isLoad = true;
                    return;
                }
                BaseNodeWindow CurWindow = NodeWindowManager.Instance.GetCurrentWindow();
                //处理window级的鼠标消息
                if (null != CurWindow)
                {
                    NodeEditorEventManager.Instance.ProcessWindowEvent(Event.current, CurWindow.WindowData.PageId);
                }
                if (null != CurWindow)
                {
                    BeginWindows();

                    CurWindow.DrawWindow();

                    EndWindows();

                }
                if (null != CurWindow)
                {
                    CurWindow.LinkNode();
                }
            }
            GUI.EndScrollView();
            Repaint();
        }

        private void DrawLeftWindow()
        {

            GUILayout.BeginHorizontal();
            GUILayout.Space(position.width - 200);
            mainData = (MainDataScriptableObject)EditorGUILayout.ObjectField(mainData, typeof(MainDataScriptableObject), false);
            if (mainData == null)
            {
                var loadedObj = AssetDatabase.LoadAssetAtPath<MainDataScriptableObject>(EditorDataSaveUtilities.Instance.MainFileSavePath);
                if (loadedObj != null)
                {
                    mainData = loadedObj;
                }
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Space(position.width - 200);
            if (mainData != null && NodeWindowManager.Instance.IsInit)
            {
                EditorDataSaveUtilities.Instance.MainFileSavePath = AssetDatabase.GetAssetPath(mainData);
                NodeWindowManager.Instance.GetSelectorWindow().Draw();
            }
            GUILayout.EndHorizontal();

        }


        void Update()
        {
            if (EditorApplication.isCompiling)
            {
                mainData = null;
                isLoad = false;
                NodeWindowManager.Instance.IsInit = false;
                Close();
            }

        }
     
    }
}